package mysql

import (
	"class-project/global"
	"gorm.io/gorm"
)

//用户表

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);not null;"`
	Password string `gorm:"type:char(32);not null;"`
	Phone    string `gorm:"type:char(11);not null;"`
}

//课程表

type Class struct {
	gorm.Model
	Name   string  `gorm:"type:varchar(20);not null;comment:课程名称"`
	Price  float64 `gorm:"type:decimal(10,2);not null;comment:课程费用"`
	Num    int64   `gorm:"type:int(10);not null;comment:报名人数"`
	CartId int64   `gorm:"type:int(10);not null;"`
	Cart   Cart    `gorm:"foreignKey:CartId"`
}

//购物车表

type Cart struct {
	gorm.Model
	SumPrice float64 `gorm:"type:decimal(10,2);not null;"`
	Num      string  `gorm:"type:varchar(256);not null;"`
}

func (u *User) Login(username string) error {
	return global.Db.Where("username", username).Find(&u).Limit(1).Error
}

//搜索

func (u *User) Sous(username string) error {
	return global.Db.Where("username", "%"+username+"%").Find(&u).Limit(1).Error
}

// 课程添加

func (c *Class) Create() error {
	return global.Db.Create(&c).Error
}

// 课程列表

func (c *Class) List() ([]Class, error) {
	var list []Class
	err = global.Db.Where("name", c.Name).Find(&list).Error
	return list, err
}

//关联查询

func (c *Class) SearCh() ([]Class, error) {
	var list []Class
	err = global.Db.Preload("Class").Preload("Cart").Find(&list).Limit(1).Error
	return list, err
}
